package com.gray.blog.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;

/**
 * Created  By zhoux 2019/05/13
 **/
@Slf4j
public class JsonObjectUtil {

    private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();


    public static <T> T getObjectFromJson(String data, String successKey, String successValue, String dataKey, Class<T> dataValue) {
        if (StrUtil.isBlank(data)) {
            return null;
        }
        JSONObject jsonObject = JSONUtil.parseObj(data);
        String successValueResult = (String) jsonObject.get(successKey);
        if (!StrUtil.equals(successValue, successValueResult)) {
            log.error("JsonObjectUtil.getObjectFromJson not success data:{}", data);
            return null;
        }
        return gson.fromJson(jsonObject.get(dataKey).toString(), dataValue);
    }

    public static Gson getGson() {
        return gson;
    }

}
